package com.childguo.Auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Data;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
public class JwtAuth<T> {

    String secret_;

    public JwtAuth() {
        this.secret_ = "childguo";
    }

    public String genToken(String claimName, T data){
        Map<String,T> claims = new HashMap<>();
        claims.put(claimName,data);

        return JWT.create()
                .withClaim(claimName,claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60))
                .sign(Algorithm.HMAC256(this.secret_));
    }

    public Claim decodeToken(String token, String claimName){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(this.secret_)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        return claims.get(claimName);
    }

    public static void main(String[] args) {
        System.out.println(new JwtAuth<>().secret_);
    }
}
